﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SlamCms.SharePoint.Migration
{
	public class MigratableContentType : IMigratable
    {
        #region Properties
        public string ParentName { get; set; }
        public string ParentScope { get; set; }
        public string Name { get; set; }
        public string Group { get; set; }
        public string Scope { get; set; }
        public List<MigratableFieldLink> FieldLinks { get; set; }

        #endregion

        public MigratableContentType()
        {
            this.FieldLinks = new List<MigratableFieldLink>();
        }

        #region Serialization

        public XElement ToXml()
        {
            XElement node = new XElement("ContentType");
            node.Add(new XAttribute("Name",Name));
            node.Add(new XAttribute("Group",Group));
            node.Add(new XAttribute("Scope",Scope));
            node.Add(new XAttribute("ParentName", ParentName));
            node.Add(new XAttribute("ParentScope", ParentScope));
            node.Add(FieldLinksToXml());

            return node;
        }

        public void FromXml(XElement element)
        {
            this.Name = element.Attribute("Name").Value;
            this.Group = element.Attribute("Group").Value;
            this.Scope = element.Attribute("Scope").Value;
            this.ParentName = element.Attribute("ParentName").Value;
            this.ParentScope = element.Attribute("ParentScope").Value;
            FieldLinksFromXml(element);
        }

        private XElement FieldLinksToXml()
        {
            XElement node = new XElement("FieldLinks");
            foreach (MigratableFieldLink fL in this.FieldLinks)
            {
                node.Add(fL.ToXml());
            }
            return node;
        }

        private void FieldLinksFromXml(XElement node)
        {
            XElement fieldLinks = node.Element("FieldLinks");
            if (fieldLinks.HasElements)
            {
                foreach (XElement child in fieldLinks.Elements())
                {
                    MigratableFieldLink fieldLink = new MigratableFieldLink();
                    fieldLink.FromXml(child);
                    this.FieldLinks.Add(fieldLink);
                }
            }
        }
        
        #endregion
    }
}
